<template>
  <div class="flex flex-col w-full h-full p-2 ">
    <div class="flex flex-row w-full " style="margin-bottom: 8px">
      <el-select
        v-model="modalName"
        placeholder="请选择模型"
        style="margin-right: 16px"
      >
        <el-option
          v-for="item in modalOpt"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-input
        v-model="inputApiKey"
        placeholder="请输入API-KEY"
        style="margin-right: 16px"
      />
    </div>
    <div class="flex flex-row w-full " style="margin-bottom: 8px">
      <el-checkbox v-model="needOutFeishu">发送到飞书</el-checkbox>

      <el-input
        v-model="表格id"
        placeholder="请输入网址"
        style="margin-right: 16px"
      />
      <el-input
        v-model="inputTitle"
        placeholder="标题(选填)"
        style="margin-right: 16px"
      />
      <el-input
        v-model="inputOriginUrl"
        placeholder="原始地址(选填)"
        style="margin-right: 16px"
      />
      <el-button type="danger" @click="handleSubmit">提交</el-button>
      <el-button type="primary" @click="checkAllStatus">查询</el-button>
      <el-button @click="clearTable">清空</el-button>
    </div>

    <div class="flex flex-row w-full " style="margin-bottom: 8px">
      <el-input
        v-model="inputUrl"
        placeholder="请输入网址"
        style="margin-right: 16px"
      />
      <el-input
        v-model="inputTitle"
        placeholder="标题(选填)"
        style="margin-right: 16px"
      />
      <el-input
        v-model="inputOriginUrl"
        placeholder="原始地址(选填)"
        style="margin-right: 16px"
      />
      <el-button type="danger" @click="handleSubmit">提交</el-button>
      <el-button type="primary" @click="checkAllStatus">查询</el-button>
      <el-button @click="clearTable">清空</el-button>
    </div>

    <el-table :data="tableData" stripe border style="width: 100%">
      <el-table-column
        prop="url"
        label="url"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column prop="name" label="标题"></el-table-column>
      <el-table-column prop="originUrl" label="原始地址"></el-table-column>

      <el-table-column prop="taskId" label="taskId"></el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <div v-if="scope.row.status === 'SUCCEEDED'" style="color: green">
            {{ scope.row.status }}
          </div>
          <div v-if="scope.row.status === 'FAILED'" style="color: orangered">
            {{ scope.row.status }}
          </div>
          <div
            v-if="scope.row.status === 'PENDING'"
            style="color: cornflowerblue"
          >
            {{ scope.row.status }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="fileUrl"
        label="文件地址"
        width="240"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="showTxt(scope.row)"
            v-if="scope.row.status === 'SUCCEEDED'"
            >展示</el-button
          >
          <el-button
            size="mini"
            type="primary"
            @click="copyTxt(scope.row)"
            v-if="scope.row.status === 'SUCCEEDED'"
            >复制
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="文案" :visible.sync="dialogVisible">
      <el-input
        type="textarea"
        style="font-size: 24px"
        :autosize="{ minRows: 2 }"
        placeholder="请输入内容"
        v-model="curTxt"
      >
      </el-input>
    </el-dialog>
  </div>
</template>
<script>
import * as $http from "@/net/axiosMgr";
const axios = require("axios");

export default {
  name: "PageAnalysis",
  data() {
    return {
      modalName: "paraformer-v1",
      modalOpt: [
        {
          value: "paraformer-v1",
          label: "paraformer-v1"
        },
        {
          value: "paraformer-8k-v1",
          label: "paraformer-8k-v1"
        },
        {
          value: "paraformer-mtl-v1",
          label: "paraformer-mtl-v1"
        },
        {
          value: "paraformer-v2",
          label: "paraformer-v2"
        },
        {
          value: "paraformer-8k-v2",
          label: "paraformer-8k-v2"
        }
      ],
      inputApiKey: "sk-444e275622d245eabce65ed25a534899",
      inputUrl: "",
      inputTitle: "",
      inputOriginUrl: "",
      tableData: [],
      curTxt: null,
      dialogVisible: false,
      needOutFeishu: false,
      inputFeishuTableId: "SicEsM38QhutSCtgy1wc7hiln6e",
      inputFeishuTableSheetId: "14f41e"
    };
  },
  methods: {
    showTxt(row) {
      console.warn(row);
      // this.curTxt = "asdsadsadsadasdasdas a sda ds aas da da a das da d aas das d";
      this.curTxt = row.txt;

      this.dialogVisible = true;
    },
    copyTxt(row) {
      this.curTxt = row.txt;
      this.copyToClipboard();
    },
    handleSubmit() {
      if (!this.inputUrl || this.inputUrl === "") {
        this.$message.error("请填写网址");
        return;
      }

      $http
        .post(
          "/api/v1/services/audio/asr/transcription",
          {
            model: this.modalName,
            input: {
              file_urls: [this.inputUrl]
            }
          },
          {
            Authorization: "Bearer " + this.inputApiKey,
            "Content-Type": "application/json",
            "X-DashScope-Async": "enable"
          }
        )
        .then(res => {
          console.warn(res);
          this.tableData.push({
            url: this.inputUrl,
            name: this.inputTitle,
            originUrl: this.inputOriginUrl,

            status: res.output.task_status,
            taskId: res.output.task_id,
            txt: null
          });

          this.inputUrl = null;
          this.inputTitle = null;
          this.inputOriginUrl = null;
        })
        .catch(e => {
          this.$message.error(e);
        });
    },
    checkAllStatus() {
      this.tableData.forEach(item => {
        console.log(item.status);
        if (item.status === "PENDING") {
          console.log("PENDING");
          this.checkStatus(item.taskId);
        }
      });
    },
    checkStatus(taskId) {
      if (!taskId || taskId === "") {
        return;
      }

      $http
        .post(
          "/api/v1/tasks/" + taskId,
          {},
          {
            Authorization: "Bearer " + this.inputApiKey
            // "Content-Type": "application/json",
            // "X-DashScope-Async": "enable"
          }
        )
        .then(res => {
          console.warn(res);

          // FAILED SUCCEEDED PENDING
          // task_id
          // res.output.results[0].subtask_status
          // res.output.results[0].subtask_statusresults[0].file_url

          let item = this.tableData.find(item => {
            return item.taskId === taskId;
          });
          if (item && res.output.results) {
            item.status = res.output.results[0].subtask_status;
            item.fileUrl = res.output.results[0].transcription_url;
            // https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/paraformer-v2/20250224/14%3A12/76247106-5234-4c5d-ad84-998b430e9e29-1.json?Expires=1740463975&OSSAccessKeyId=LTAI5tQZd8AEcZX6KZV4G8qL&Signature=xrT6Gy2fwUAiCGgfBlSA%2B6a5LwQ%3D

            if (item.status === "SUCCEEDED") {
              this.getJsonTxt(item.fileUrl, item.taskId);
            }
          }
        })
        .catch(e => {
          this.$message.error(e);
        });
    },
    getJsonTxt(fileUrl, taskId) {
      axios
        .get(fileUrl)
        .then(response => {
          // 获取 JSON 数据
          const jsonData = response.data.transcripts[0].text;
          console.log("Result:", jsonData);

          let item = this.tableData.find(item => {
            return item.taskId === taskId;
          });
          if (item) {
            item.txt = jsonData;
          }
        })
        .catch(error => {
          console.error("Error downloading or parsing the JSON file:", error);
        });
    },
    async copyToClipboard() {
      try {
        await navigator.clipboard.writeText(this.curTxt); // 使用 Clipboard API
        this.$message("复制成功");
      } catch (err) {
        console.error("复制失败", err);
        this.$message.error("复制失败");
      }
    },

    clearTable() {
      this.tableData = [];
      this.inputUrl = null;
      this.inputTitle = null;
      this.inputOriginUrl = null;
    }
  }
};
</script>

<style scoped>
.hide-scrollbar {
  /* 针对Firefox */
  scrollbar-width: none;

  /* 针对Chrome、Edge和Safari */
  -ms-overflow-style: none; /* IE and Edge */
}

.hide-scrollbar::-webkit-scrollbar {
  display: none; /* Chrome, Safari and Opera */
}
</style>
